package com.javaee.weixin.xiaochengxu.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;


/**
 * 
 * Md5 加密<br>
 * 
 * @author songzx
 * @version 1.0,2017年4月22日 下午2:45:06
 * @since wxapi 0.0.1
 */
public class MD5Util {
	private static final Logger log = org.slf4j.LoggerFactory.getLogger(MD5Util.class);
	private static MD5Util md5Util;
	private String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	private MD5Util() {
	}

	public static MD5Util getInstance() {
		if (md5Util == null) {
			md5Util = new MD5Util();
		}
		return md5Util;
	}

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param b
	 *            字节数组
	 * @return 16进制字串
	 */
	public String byteArrayToHexString(byte[] b) {
		StringBuilder resultSb = new StringBuilder();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public String compile(String origin) {
		if (StringUtils.isBlank(origin)) {
			return "";
		}
		String resultString = origin;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
		}
		return resultString;
	}

	public String compileWithSalt(String origin, String salt) {
		String resultString = origin + "{" + salt + "}";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
		}
		return resultString;
	}
	
	public static void main(String[] args) {
		System.out.println(MD5Util.getInstance().compile("appid=wx15a3b07359b8ab28&attach=XXX店地址&body=XXX店-外卖支付&detail=支付详情&device_info=WEB&fee_type=CNY&limit_pay=no_credit&mch_id=1463015102&nonce_str=6343c816669e47e5a8a77d5d7c4c7f99&openid=oVx_t0GZi6wepbE2DwePH2oVZeLE&out_trade_no=cc3c0462b89e4e02aa7d36249eec3be4&product_id=fe6b4eb74e044b42830b02cbf4140362&sign_type=MD5&spbill_create_ip=192.168.1.105&time_expire=20170422094242&time_start=20170422091242&total_fee=0.0.1&trade_type=JSAPI&key=key"));
	}
}
